package middleware

import (
	"sync"
	"webssh/src/logger"
	"webssh/src/response"

	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func ParseUserToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader(viper.GetString("server.tokenKey"))
		if token == "" {
			c.Next()
			return
		}
		// If Casdoor is enabled, please uncomment the code below.
		// Alternatively, if you need to parse user tokens,
		// you can implement your own ParseJwtToken method.

		// claims, err := casdoorsdk.ParseJwtToken(token)
		once := sync.Once{}
		once.Do(func() {
			client = casdoorClient()
		})
		claims, err := client.ParseJwtToken(token)
		if err != nil {
			logger.Info("authentication failed")
			response.Response(c, *response.ErrJwtVerify, nil)
			c.Abort()
			return
		}
		c.Set("username", claims.Name)
		c.Set("tenantId", claims.Properties["tenantId"])

		c.Next()
	}
}

var client *casdoorsdk.Client

func casdoorClient() *casdoorsdk.Client {
	return casdoorsdk.NewClient(
		viper.GetString("casdoor.endpoint"),
		viper.GetString("casdoor.clientId"),
		viper.GetString("casdoor.clientSecret"),
		viper.GetString("casdoor.certificate"),
		viper.GetString("casdoor.organizationName"),
		viper.GetString("casdoor.applicationName"),
	)
}
